package com.ruiysoft.controller.order;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruiysoft.controller.integral.WxIntegralApi;
import com.ruiysoft.controller.order.api.CusorderApi;
import com.ruiysoft.controller.order.util.OrderWechatUtil;
import com.ruiysoft.controller.order.vo.*;
import com.ruiysoft.entity.ModelApiResponse;
import com.ruiysoft.entity.common.UserInfo;
import com.ruiysoft.entity.order.OrderMain;
import com.ruiysoft.entity.order.OrderReceiverInfo;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.order.IOrderWechatService;
import com.ruiysoft.service.order.bean.OrderDto;
import com.ruiysoft.service.order.bean.OrderIntfResultDto;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-10-27T20:58:54.914+08:00")

@RestController
public class CusorderApiController implements CusorderApi {

    private static final Logger log = LoggerFactory.getLogger(CusorderApiController.class);

    private final ObjectMapper objectMapper;

    private final HttpServletRequest request;

    private final IOrderWechatService orderWechatService;

    @Autowired
    private WxIntegralApi integralApi;

    @org.springframework.beans.factory.annotation.Autowired
    public CusorderApiController(ObjectMapper objectMapper, HttpServletRequest request, IOrderWechatService orderWechatService) {
        this.objectMapper = objectMapper;
        this.request = request;
        this.orderWechatService = orderWechatService;
    }

    private UserInfo getCurrUserInfo() {
        Long shopId = LoginContextUtil.instance().getEntryMicroShop().getId();

        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();

        return new UserInfo()
                .setPersonnelId(personnel.getId())
                .setShopId(shopId)
                .setMemberFlag(personnel.getMemberFlag())
                .setMemberLevel(personnel.getMemberLevel())
                .setOpenid(personnel.getOpenid());
    }

    @Override
    public Result<ModelApiResponse> cusorderCancelOrderNoGet(@ApiParam(value = "订单号", required = true) @PathVariable("orderNo") String orderNo) {
		return orderWechatService.orderCancel(orderNo, getCurrUserInfo().getPersonnelId(),"用户主动取消");
    }

    @Override
    public Result<ModelApiResponse> cusorderConfirmreceiptOrderNoGet(@ApiParam(value = "订单号", required = true) @PathVariable("orderNo") String orderNo) {
		Result<OrderMain> orderMainResult = orderWechatService.orderConfirmReceipt(orderNo, getCurrUserInfo().getPersonnelId());
        Result<ModelApiResponse> result = new Result<ModelApiResponse>();
        result.setBizCode(orderMainResult.getBizCode());
        result.setBizMessage(result.getBizMessage());
        ModelApiResponse response = new ModelApiResponse();
        response.setSuccess(result.isSuccess());
        result.setData(response);
        return result;
    }

    @Override
    public Result<OrderReceiverInfoVo> cusorderLastestreceiverinfoGet() {
        OrderReceiverInfo info = orderWechatService.findLastestReceiverInfo(getCurrUserInfo().getPersonnelId());
        OrderReceiverInfoVo vo = OrderWechatUtil.INSTANCE.orderReceiverInfo2Vo(info);
        return ResultGenerator.genSuccessResult(vo);
    }

    //todo 没有校验当前用户身份与订单是否匹配，可能存在信息泄露风险
    @Override
    public Result<OrderDetailCusVo> cusorderOrderdetailOrderNoGet(@ApiParam(value = "订单号", required = true) @PathVariable("orderNo") String orderNo) {
        UserInfo userInfo = getCurrUserInfo();
        /*OrderDto dto = IdentityConst.SHOPKEEPER == userInfo.getIdentityType()?
                orderWechatService.findOrderWithDetailByOrderNo(userInfo.getShopId(),orderNo):
                orderWechatService.findOrderWithDetailByOrderNo(getCurrUserInfo(),orderNo);*/
        OrderDto dto = orderWechatService.findOrderWithDetailByOrderNo(userInfo,orderNo);
        if(dto == null)
            return ResultGenerator.genFailResult("OrderDto为空!");

        OrderDetailCusVo vo = OrderWechatUtil.INSTANCE.orderDto2OrderDetailCusVo(dto);
        return null == vo ? ResultGenerator.genFailResult("未查询到订单详情") : ResultGenerator.genSuccessResult(vo);
    }

    @Override
    public Result<PageInfo<OrderListCusVo>> cusorderOrderlistGet(@NotNull @ApiParam(value = "分页页码", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页条数", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, @ApiParam(value = "订单状态值") @Valid @RequestParam(value = "status", required = false) String status) {
        String[] statusArr = Optional.ofNullable(status).map(s -> s.split(",")).orElse(null);
        Set<Integer> statusSet = Optional.ofNullable(statusArr)
                .map(sarr ->
                        Arrays.stream(sarr)
                                .filter(StringUtils::isNotBlank)
                                .map(s -> Integer.valueOf(s.trim()))
                                .collect(Collectors.toSet()))
                .orElse(null);
        PageInfo<OrderDto> dtos = orderWechatService.findOrders(getCurrUserInfo(), statusSet, pageStart, pageSize);
        List<OrderListCusVo> vos = OrderWechatUtil.INSTANCE.orderDtos2OrderListCusVos(dtos.getList());
        return ResultGenerator.genSuccessResult(new PageInfo<OrderListCusVo>(vos, dtos));
    }

    /*
     *  TODO 支付过程步骤：1、前端开始（下面这个未实行方法）；2、前端支付完成；3、后端回调确认。
     *  当支付失败时，因为步骤1是必然成功的，所以必然留下支付路径。
     */
    //public Result<Map> frontendGoingPay(){};

    @Override
    public Result<Void> frontendPaid(
            @ApiParam(value = "订单号", required = true) @PathVariable("orderNo") String orderNo,
            @ApiParam(value = "是否支付成功", required = true) @PathVariable("isPaidSuccess") boolean isPaidSuccess) {
        //扣减虚拟
        return orderWechatService.frontendPaid(getCurrUserInfo(),orderNo,isPaidSuccess);
    }

    @Override
    public Result<Map> cusorderPlacePost(@ApiParam(value = "订单信息") @Valid @RequestBody OrderPlaceCusVo orderPlaceVo) {
        ShopVO shopVO = new ShopVO();
        shopVO.setShopID(getCurrUserInfo().getShopId());

        OrderBuyerVO buyerVO = new OrderBuyerVO();
        buyerVO.setMemberLevel(Optional.of(getCurrUserInfo().getMemberLevel() == null ? 0 : getCurrUserInfo().getMemberLevel()));
        buyerVO.setPersonID(getCurrUserInfo().getPersonnelId());
        buyerVO.setVirtualCoin(getVirtualCoinBalance());

        Result<Map> result = new Result<>();
        Result<OrderIntfResultDto> prePlaceResult = orderWechatService.orderPrePlace(shopVO, buyerVO, orderPlaceVo);
        if(!prePlaceResult.isSuccess()){
            result.setBizCode(prePlaceResult.getBizCode());
            result.setBizMessage(prePlaceResult.getBizMessage());
            return result;
        }

        Result<OrderIntfResultDto> placeResult = orderWechatService.orderPlace(getCurrUserInfo(), prePlaceResult.getData());
        Result<Map> resp = OrderWechatUtil.INSTANCE.placeOrderResult2ModelApiResponse(placeResult);
        return resp;
    }

    @Override
    public Result<OrderPlaceResponseVo> cusorderPreplacePost(@ApiParam(value = "订单信息") @Valid @RequestBody OrderPlaceCusVo orderPlaceVo) {
        ShopVO shopVO = new ShopVO();
        shopVO.setShopID(getCurrUserInfo().getShopId());

        OrderBuyerVO buyerVO = new OrderBuyerVO();
        if(getCurrUserInfo().getMemberLevel() != null)
            buyerVO.setMemberLevel(Optional.of(getCurrUserInfo().getMemberLevel()));
        else
            buyerVO.setMemberLevel(Optional.of(0));

        buyerVO.setPersonID(getCurrUserInfo().getPersonnelId());
        buyerVO.setVirtualCoin(getVirtualCoinBalance());

        Result<OrderIntfResultDto> prePlaceResult = orderWechatService.orderPrePlace(shopVO, buyerVO, orderPlaceVo);
        OrderPlaceResponseVo responseVo = OrderWechatUtil.INSTANCE.orderPrePlaceResultDto2OrderPlaceResponseVo(prePlaceResult.getData());
        Result<OrderPlaceResponseVo> result = new Result<>();
        result.setBizMessage(prePlaceResult.getBizMessage());
        result.setBizCode(prePlaceResult.getBizCode());
        result.setData(responseVo);

        if(log.isDebugEnabled()) {
            log.debug("订单信息：{}", JSON.toJSONString(result));
        }
        return result;
    }

    private Optional<Long> getVirtualCoinBalance(){
        Result<Long> result = integralApi.wxIntegralGet();
        return Optional.ofNullable(result.isSuccess()?result.getData():null);
    }


}
